package io.geekidea.boot.config;

import com.hwtx.form.domain.def.FormProperties;
import com.hwtx.form.domain.meta.RacMeta;
import io.geekidea.boot.auth.cache.LoginCache;
import io.geekidea.boot.framework.exception.BusinessException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.hwtx.form.domain.FormConstants.FORM_INFO_URL;
import static com.hwtx.form.domain.FormConstants.FORM_MANAGE_HANDLE_NAME;

@Component
@Slf4j
public class FormDataPermissionFilter extends BaseDataPermissionFilter<FormProperties> {
    @Resource
    private RacMeta racMeta;

    @Override
    public boolean filter0(FormProperties formProperties) {
        RacMeta.DataPerms dataPerms = racMeta.getDataPermsByFunPerm(LoginCache.get().getRoleIds(), FORM_INFO_URL);
        AtomicBoolean match = new AtomicBoolean(false);
        if (dataPerms.getDataPermScope() != null) {
            match.set(switch (dataPerms.getDataPermScope()) {
                case NO_DATA_PERMISSIONS -> false;
                case PERSONAL_DATA_PERMISSIONS ->
                        Objects.equals(formProperties.getMeta().getCreateBy(), LoginCache.get().getUsername());
                case SPECIFY_ORG_DATA_PERMISSIONS -> {
                    if (CollectionUtils.isNotEmpty(dataPerms.getScopeOrgIds())) {
                        yield !CollectionUtils.intersection(LoginCache.get().getOrgIds(), dataPerms.getScopeOrgIds()).isEmpty();
                    }
                    yield false;
                }
                case ORG_DATA_PERMISSIONS, ORG_AND_FOLLOWING_DATA_PERMISSIONS ->
                        throw new BusinessException("暂不支持");
                case ALL_DATA_PERMISSIONS -> true;
            });
        }
        if (match.get() && MapUtils.isNotEmpty(dataPerms.getDataPermProVal())) {
            dataPerms.getDataPermProVal().forEach((key, value) -> {
                if (value == null) {
                    return;
                }
                if (value instanceof Map<?, ?>) {
                    value = ((Map<?, ?>) value).get("value");
                }
                String[] values = value.toString().split(",");
                value = values[values.length - 1];
                if (Objects.equals(key, "system") && !Objects.equals(BooleanUtils.toBoolean(value.toString()), formProperties.getSystem())) {
                    match.set(false);
                }
            });
        }
        return match.get();
    }

    @Override
    public String getType() {
        return FORM_MANAGE_HANDLE_NAME;
    }
}
